import fetch from 'dva/fetch';
import router from 'umi/router';
import { routerRedux } from 'dva/router';
import * as requesturl from "@/services/request-url";
import { message } from 'antd';

const codeMessage = {
  200: '服务器成功返回请求的数据。',
  201: '新建或修改数据成功。',
  202: '一个请求已经进入后台排队（异步任务）。',
  204: '删除数据成功。',
  400: '发出的请求有错误，服务器没有进行新建或修改数据的操作。',
  401: '用户没有权限（令牌、用户名、密码错误）。',
  403: '用户得到授权，但是访问是被禁止的。',
  404: '发出的请求针对的是不存在的记录，服务器没有进行操作。',
  406: '请求的格式不可得。',
  410: '请求的资源被永久删除，且不会再得到的。',
  422: '当创建一个对象时，发生一个验证错误。',
  500: '服务器发生错误，请检查服务器。',
  502: '网关错误。',
  503: '服务不可用，服务器暂时过载或维护。',
  504: '网关超时。'
};

const checkStatus = (response) => {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }
  console.log(response);
  const errortext = codeMessage[response.status] || response.statusText;
  const error = new Error(errortext);
  error.name = response.status;
  error.response = response;
  throw error;
};



//token

export async function getToken() {
  let token = undefined;
  const casTokenUrl = `${requesturl.login}/cas/jwt/token.do`;
  await fetch(casTokenUrl, {
    method: 'POST',
    credentials: 'include',
  }).then(res =>
    res.json().then(data => {
      const { returnStatus, returnInfo } = data

      if (returnStatus == 200) {
        const currentTime = new Date().getTime();
        window.tokenLastUpdateTime = currentTime;
        window.epmToken = returnInfo;
        token = returnInfo;
        sessionStorage.setItem("token", token)
      } else if (returnStatus == 401) { // 未登录
        // window.location = `http://172.16.193.25:9009` + returnInfo;
        let a = document.createElement("a")
        a.href = `${requesturl.login}/cas/jwt/login.do`;
        a.click();
      }
    })
  );
}



/**
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 * @return {object}           An object containing either "data" or "err"
 */

export default async function request(url, option) {
  const defaultOptions = {
    credentials: 'include',
    //在请求头中加上token
    headers: {
      'p-user-token': sessionStorage.getItem("token") || "",
    }
  };
  const newOptions = { ...defaultOptions, ...option };
  if (newOptions.method === 'POST' || newOptions.method === 'PUT' || newOptions.method === 'DELETE') {
    newOptions.headers = {
      Accept: 'application/json;charset=UTF-8',
      'Content-Type': 'application/json;charset=UTF-8',
      // 'Access-Control-Allow-Origin': request.getHeader("origin"),
      // 'Access-Control-Allow-Credentials': true,
      // 'access-control-allow-headers':"Authorization, Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, X-Requested-By, If-Modified-Since, X-File-Name, X-File-Type, Cache-Control, Origin",
      // 'access-control-allow-methods':"GET, POST, OPTIONS, PUT, DELETE",
      // 'access-control-expose-headers': "Authorization",
      ...newOptions.headers
    }
    if (!(newOptions.body instanceof FormData) && typeof newOptions.body !== 'string') {

      const { body } = newOptions;
      /* if (body) {
          const params = new URLSearchParams();
          Object.keys(body)
              .forEach((item) => {
                  return params.append(item, body[item]);
              });
          newOptions.body = params;
      } */
      newOptions.body = JSON.stringify(body);
    }
  }

  const newUrl = url;
  // const newUrl = url.indexOf('?') > -1 ? `${url}&_tips=${Date.now()}` : `${url}?_tips=${Date.now()}`;
  return fetch(newUrl, newOptions)
    .then(checkStatus)
    .then((response) => {
      let resarr = response.url.split("/")
      if (resarr.indexOf("download?path=") > -1) {
        return response.blob();
      } else {
        return response.json();
      }
    }).then((result) => {
      if ('code' in result && (result.code.toString() === '403' || result.code.toString() === '3')) {
        throw result;
      }
      return result;
    })
    .catch((e) => {
      console.log(e);
      if ('code' in e && (e.code.toString() === '403' || e.name.toString() === '403')) {
        /* eslint-disable no-underscore-dangle */
        console.log(requesturl.login);
        getToken()
        message.destroy();
        message.error(e.msg);
        return e;
      } else {
        const status = e.code;
        if (status === "403") {
          console.log("222222222");
          // @HACK 跳转到登录页
          /* eslint-disable no-underscore-dangle */
          window.g_app._store.dispatch({
            type: 'user/token'
          });
          return;
        }
        // //判断状态
        // if (status === 403) {
        // router.push('/exception/403');
        // return;
        // }
        // if (status <= 504 && status >= 500) {
        // router.push('/exception/500');
        // return;
        // }
        // if (status >= 404 && status < 422) {
        // router.push('/exception/404');
        // }
      }
    });
}